import cn.le.util.info.HostInfo;
import handler.HttpFileServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class HttpFileServer {

  private static final String DEFAULT_URL = "/netty-fileServer/src/main/";

  public static void main(String[] args) {
    HttpFileServer server = new HttpFileServer();
    server.run(DEFAULT_URL);
  }


  public void run(final String url){
    EventLoopGroup boosGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap.group(boosGroup,workerGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {
              ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
              ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536));
              ch.pipeline().addLast("http-encoder",new HttpResponseEncoder());
              ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());
              ch.pipeline().addLast("fileServerHandler",new HttpFileServerHandler(url));
            }
          }).option(ChannelOption.SO_BACKLOG,128)
            .childOption(ChannelOption.SO_KEEPALIVE,Boolean.TRUE);

      ChannelFuture future = bootstrap.bind(HostInfo.HOST_NAME,HostInfo.PORT).sync();
      System.out.println("文件目录服务器启动成功!网址是: "
        + "127.0.0.1:"+HostInfo.PORT+url);
      future.channel().closeFuture().sync();
    }catch (Exception e){
      e.printStackTrace();
    }finally {
      boosGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }

}
